// 定义通用树节点类型
interface TreeNode {
  [key: string]: any;
}

// 定义配置类型
interface TreeConfig {
  id: string | number;
  parentId: string | number;
  childrenList: string;
}

/**
 * 将平铺数据转为树形结构
 * @param data 节点数组
 * @param id 节点唯一标识字段名或键值
 * @param parentId 父节点标识字段名
 * @param children 子节点字段名
 */
export function handleTree<T extends TreeNode>(
  data: T[],
  id: string | number,
  parentId: string = 'parentId',
  children: string = 'children',
): T[] {
  const config: TreeConfig = {
    id: id || 'id',
    parentId: parentId || 'parentId',
    childrenList: children || 'children',
  };
  const childrenListMap: { [key: string | number]: T[] } = {};
  const nodeIds: { [key: string | number]: T } = {};
  const tree: T[] = [];

  for (const d of data) {
    const pid = d[config.parentId as keyof T];
    if (!childrenListMap[pid]) {
      childrenListMap[pid] = [];
    }
    childrenListMap[pid].push(d);
    nodeIds[d[config.id as keyof T]] = d;
  }

  for (const d of data) {
    const pid = d[config.parentId as keyof T];
    if (!nodeIds[pid]) {
      tree.push(d);
    }
  }

  for (const t of tree) {
    adaptToChildrenList(t);
  }

  function adaptToChildrenList(o: T): void {
    const key = config.childrenList;
    const idKey = config.id as keyof T;

    if (childrenListMap[o[idKey]]) {
      // 类型断言处理泛型索引赋值问题
      (o as Record<string | number, any>)[key] = childrenListMap[o[idKey]];
    }

    const childrenArray = (o as Record<string | number, any>)[key];

    if (childrenArray) {
      for (const c of childrenArray) {
        adaptToChildrenList(c);
      }
    }
  }

  return tree;
}

export function getName(lid: any, id: any, list: any[], name: string) {
  if (!id || !Array.isArray(list) || list.length === 0) return '';

  const foundItem = list.find((item) => item[lid] == id);
  return foundItem ? foundItem[name] : '';
}

// 添加日期范围
export function addDateRange(params: any, dateRange: any, propName: string = '') {
  const search = { ...params }; // 复制原对象避免污染
  dateRange = Array.isArray(dateRange) ? dateRange : [];

  if (dateRange.length === 2) {
    // const prefix = propName ? `params[${propName}]` : 'params';

    // 扁平化命名 + 自动编码
    search[`beginTime`] = dateRange[0];
    search[`endTime`] = dateRange[1];
  }

  return search;
}
